// https://www.lintcode.com/problem/distinct-subsequences/

public class Solution {
    /**
     * @param S: A string
     * @param T: A string
     * @return: Count the number of distinct subsequences
     */
    public int numDistinct(String S, String T) {
        // write your code here
        /*
        根据题目提供的例子，建一张二维表：
            r a b b b i t (S)
        r 0 1 1 1 1 1 1 1   
        a 0 0 1 1 1 1 1 1
        b 0 0 0 1 2 3 3 3
        b 0 0 0 0 1 3 3 3 ＃ 关键在第一个3
        i 0 0 0 0 0 0 3 3
        t 0 0 0 0 0 0 0 3
        (T)
        dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0)
        */
        int[][] cache = new int[T.length() + 1][S.length() + 1];
        for (int i = 0; i < cache.length; ++i) {
            int v = (i == 0) ? 1 : 0;
            Arrays.fill(cache[i], v);
        }
        for (int i = 1; i < cache.length; ++i) {
            for (int j = 1; j < cache[0].length; ++j) {
                cache[i][j] = cache[i][j - 1];
                if (T.charAt(i - 1) == S.charAt(j - 1)) {
                    cache[i][j] += cache[i - 1][j - 1];
                }
            }
        }
        return cache[T.length()][S.length()];
    }
}